<template>
    <div class="login">
        <van-nav-bar title="登录博客系统" />

        <div class="login-box">
            <!-- 用户名 -->
            <van-field v-model="username" placeholder="请输入用户名" />

            <!-- 密码 -->
            <van-field v-model="password" placeholder="请输入密码" />

            <!-- 登录 -->
            <van-button type="primary" @click="onLoginClicked">登录</van-button>
        </div>
    </div>
</template>

<script>
export default {
    data() {
        return {
            username: "",
            password: "",
        };
    },
    methods: {
        async onLoginClicked() {
            console.log(this.username, this.password);
            const { username, password } = this;
            // 非空验证
            if (!username || !password) {
                this.$notify({
                    message: "用户密码不能为空",
                });
                return;
            }
            const res = await this.$http.post("login", {
                username: username,
                password,
            });
            // 判断是否登录成功
            if (res.code !== 200) {
                this.$toast({
                    type: "fail",
                    message: res.message,
                });
                return;
            }
            // 保存用户登录状态
            window.sessionStorage.setItem("token", res.data.token);
            // 保存用户信息
            window.sessionStorage.setItem(
                "user",
                JSON.stringify(res.data.user)
            );
            // 跳转到博客页面
            this.$router.push("/blogs");
        },
    },
};
</script>

<style lang="less" scoped>
.login {
    height: 100%;
    background-color: #f3f3f3;
    // padding-top: 1px;

    .login-box {
        margin-top: 130px;

        .van-field {
            margin-bottom: 10px;
            width: 100%;
        }

        .van-button {
            width: 100%;
        }
    }
}
</style>
